package com.example.shorg.service.impl;

import com.example.shorg.dataobject.ProductInfo;
import com.example.shorg.dto.CartDTO;
import com.example.shorg.enums.ProductStatusEnum;
import com.example.shorg.enums.ResultEnum;
import com.example.shorg.exception.ShorgException;
import com.example.shorg.repository.ProductInfoRepository;
import com.example.shorg.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ProductSericeImpl implements ProductService {

    @Autowired
    private ProductInfoRepository repository;

    @Override
    public ProductInfo findOne(String productId) {
        return repository.findOne(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return repository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return repository.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo info) {
        return repository.save(info);
    }

    @Override
    public void increaseStock(List<CartDTO> cartDTOList) {

    }

    @Override
    public void descreaseStock(List<CartDTO> cartDTOList) {
        for(CartDTO cartDTO: cartDTOList){
            //根据产品id查询产品
            ProductInfo one = repository.findOne(cartDTO.getProductId());
            if(one == null){
                log.error("【产品查询】 产品为空string={}");
                throw new ShorgException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            int num = one.getProductStock() - cartDTO.getProductQuantity();
            if(num < 0){
                log.error("");
                throw new ShorgException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            //将库存在存入到表里
            one.setProductStock(num);
            repository.save(one);
        }
    }
}
